package cn.itcast.bos.action.take_delivery;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.action.base.BaseAction;
import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.service.take_delivery.PromotionService;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class PromotionAction extends BaseAction<Promotion> {
	
	@Autowired
	private PromotionService promotionService;
	
	private File titleImgFile;
	private String titleImgFileFileName;
	
	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}

	@Action(value="promotionSave",results={@Result(name="success",type="redirect",location="./pages/take_delivery/promotion.html")})
	public String pomotionSave() throws IOException{
		
		String realPath = ServletActionContext.getServletContext().getRealPath("/upload");
		String fileName =UUID.randomUUID()+titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
		File file = new File(realPath+"/"+fileName);
		FileUtils.copyFile(titleImgFile, file);
		String urlPath = ServletActionContext.getServletContext().getContextPath()+"/upload/"+fileName;
		model.setTitleImg(urlPath);
		promotionService.save(model);
		return SUCCESS;
	}
	
	@Action(value="promotion_queryPage",results={@Result(name="success",type="json")})
	public String queryPage(){
		
		Pageable pageable = new PageRequest(page-1, rows);
		
		Page<Promotion> page = promotionService.queryPage(pageable);
		pushPageDataToValueStack(page);
		return SUCCESS;
		
	}
	
}
